<template>
  <div class="container">
    <div class="app-container">
      <!-- 操作部门 -->
      <div class="role-operate">
        <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 表格 -->
      <el-table :data="list">
        <el-table-column width="200" align="center" label="角色">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column width="200" align="center" label="启用">
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else> {{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '无' }} </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" :rows="3" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row}">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="btnRoleOk(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="assignPermission(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="editRole(row)">编辑</el-button>
              <!-- 气泡确认框 -->
              <el-popconfirm
                title="确认删除该角色吗?"
                style="margin-left: 10px;"
                @onConfirm="delRole(row.id)"
              >
                <el-button slot="reference" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" style="height: 60px;" justify="end" align="middle">
        <el-pagination
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          :current-page="pageParams.page"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>

      <!-- 添加弹层对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="showDialog"
        width="500px"
        @close="btnCancel"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" size="mini" style="width:300px" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="启用">
            <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" size="mini" placeholder="请输入角色描述" type="textarea" :rows="3" style="width:300px" />
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :offset="6" :span="12">
                <el-button type="primary" size="mini" @click="btnOk">确定</el-button>
                <el-button size="mini" @click="btnCancel">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 分配权限弹出层 -->
      <el-dialog title="分配权限" :visible="showPermissionDialog" center @close="btnPermCancel">
        <el-tree
          ref="permTree"
          check-strictly
          node-key="id"
          show-checkbox
          :data="permissionList"
          :props="{label: 'name'}"
          default-expand-all
          :default-checked-keys="permIds"
        />
        <template #footer>
          <el-button size="mini" type="primary" @click="btnPermOk">确定</el-button>
          <el-button size="mini" @click="btnPermCancel">取消</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { reqGetRoleList, reqAddRole, reqUpdateRole, reqDelRole, reqGetRoleDetail, reqAssignPermission } from '@/api/role'
import { reqGetPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      // 表格的数据数组(对象数组)
      list: [],
      // 分页相关属性
      pageParams: {
        page: 1, // 当前页
        pagesize: 5, // 每页条数
        total: 0 // 总条数
      },
      // 控制添加对话框的显示/隐藏
      showDialog: false,
      // 添加角色数据对象
      roleForm: {
        name: '', // 角色名称
        description: '', // 角色描述
        state: 0 // 1启用 0未启用
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      // 控制分配权限弹出框的显示/隐藏
      showPermissionDialog: false,
      // 记录当前操作的id
      currentRoleId: null,
      // 所有的权限列表
      permissionList: [],
      // 选中的权限点
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 1. 获取角色列表
    async getRoleList() {
      const { rows, total } = await reqGetRoleList(this.pageParams)
      this.pageParams.total = total
      this.list = rows
      // 1.1 给每一个数据对象添加一个编辑标记
      this.list.forEach(item => {
        // 这种方式添加的属性不是响应式的
        // item.isEdit = false
        // 用响应式的方式给对象添加属性
        // this.$set(数据对象, 属性, 属性值)
        this.$set(item, 'isEdit', false)
        // 绑定缓存数据对象
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 2. 切换当前页
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    // 3. 点击确定按钮
    async btnOk() {
      await this.$refs.roleForm.validate()
      await reqAddRole(this.roleForm)
      this.$message.success('添加角色成功')
      this.getRoleList()

      this.btnCancel()
    },
    // 4. 点击取消按钮
    btnCancel() {
      this.roleForm = {
        name: '', // 角色名称
        description: '', // 角色描述
        state: 0 // 1启用 0未启用
      }
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 5. 编辑角色
    editRole(row) {
      // 5.1 修改行数据的编辑标记
      row.isEdit = true
      // 5.2 更新缓存中的数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 6. 点击编辑角色
    async btnRoleOk(row) {
      // 6.1 检查必填
      if (row.editRow.name && row.editRow.description) {
        // 6.2 调用更新角色的接口函数
        await reqUpdateRole({ ...row.editRow, id: row.id })
        // 6.3 提示用户
        this.$message.success('更新角色成功')
        // 6.4 更新显示数据
        // ESLint发生语法检查误判
        // eslint-disable-next-line require-atomic-updates
        // row.name = row.editRow.name
        // Object.assign('目标对象', '源对象')
        // Object.assign({ sex: '男' }, { name: '张飒', age: 17 })
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
      } else {
        this.$message.warning('角色的名称和描述必填')
      }
    },
    // 7. 删除角色
    async delRole(id) {
      // 7.1 调用删除角色的接口函数
      await reqDelRole(id)
      // 7.2 提示用户
      this.$message.success('删除角色成功')
      // 7.4 判断当前页是否只有一条数据 & 不能是第一页
      if (this.list.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page--
      }
      // 7.3 重新加载
      this.getRoleList()
    },
    // 8. 分配权限
    async assignPermission(id) {
      this.currentRoleId = id
      this.permissionList = transListToTreeData(await reqGetPermissionList(), 0)
      // 获取角色详情
      const { permIds } = await reqGetRoleDetail(id)
      this.permIds = permIds
      this.showPermissionDialog = true
    },
    // 9. 点击确定按钮
    async btnPermOk() {
      await reqAssignPermission({ id: this.currentRoleId, permIds: this.$refs.permTree.getCheckedKeys() })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },
    // 10. 关闭弹窗
    btnPermCancel() {
      this.$refs.permTree.setCheckedKeys([])
      this.showPermissionDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
.role-operate {
  padding: 20px;
}
</style>
